package com.ubb.damate.service.impl;

import java.util.Date;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.ubb.damate.util.DateUtils;
import com.ubb.damate.model.ProjectHandlingModel;
import com.ubb.damate.model.User;
import com.ubb.damate.model.Project;
import com.ubb.damate.service.ProjectHandlingServiceLocal;
import com.ubb.damate.service.ProjectHandlingServiceRemote;
import com.ubb.damate.service.UserServiceLocal;
import com.ubb.damate.service.ProjectServiceLocal;
import com.ubb.damate.service.EclipseUsageServiceLocal;

/**
 * Session Bean implementation class ProjectHandlingService
 */
@Stateless
public class ProjectHandlingService implements ProjectHandlingServiceRemote, ProjectHandlingServiceLocal {

	@PersistenceContext(unitName = "damate-pu")
	private EntityManager em;
	
	@EJB(beanName = "EclipseUsageService")
	private EclipseUsageServiceLocal	eclipseUsageService;
	
	@EJB(beanName = "UserService")
	private UserServiceLocal	userService;
	
	@EJB(beanName = "ProjectService")
	private ProjectServiceLocal	projectService;

	public Map<User, ProjectHandlingModel> getStats()
	{
		Map<User, ProjectHandlingModel> result = new HashMap<User, ProjectHandlingModel>();
		List<User> users = userService.allUser();
		for (User user : users) {
			result.put(user, getStats(user));
		}
		return result;
	}
	
	public ProjectHandlingModel getStats(User user)
	{
		ProjectHandlingModel result = new ProjectHandlingModel();
		List<Integer> nrOfCreatedProjects = eclipseUsageService.getStats(user).getProjects();
		Map<Project, List<Integer>> nrOfFiles = new HashMap<Project, List<Integer>>();
		
		List<Integer> files;
		int i, j, value;
		Date date;
		Query query;
		
		List<Project> projects = projectService.find(user.getUsername());
		for (Project project : projects) {
			// files added per month
			files = new ArrayList<Integer>();
			for (i = 1; i <= Calendar.MONTH; i++)
			{
				value = 0;
				for (j = 1; j <= 31; j++) {
					date = DateUtils.createDate(-1, i, j);
					
					query = em.createQuery("select count(f.id) from File f where f.creationDate=:arg1 and f.project=:arg2");
					query.setParameter("arg1", date);
					query.setParameter("arg2", project);
					
					try
					{
						value += Integer.parseInt("" + (Long)query.getSingleResult());
					}
					catch(Exception e)
					{}
				}
				files.add(value);
			}
			while (files.size() < 12)
				files.add(0);
			
			nrOfFiles.put(project, files);
		}
		
		result.setNrOfCreatedProjects(nrOfCreatedProjects);
		result.setNrOfFiles(nrOfFiles);
		return result;
	}
}